<?php
/**
 * Created by PhpStorm.
 * User: lcz
 * Date: 2018/8/17
 * Time: 16:52
 * 定时任务
 */

namespace app\api\controller;

use app\common\model\BuyRecord;
use app\common\model\GoodsRecord;
use think\Controller;
use think\Db;
use think\Exception;

class Task extends Controller{
	
	
	/**
	 * 开奖
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 * @throws \think\exception\PDOException
	 */
	public function openRecord(){
		$str = '========='.date('Y-m-d H:i:s')."========\r\n";
		$model = new GoodsRecord();
		//查找状态为待开奖且开奖时间小于等于当前时间的记录
		$rows = Db::name('goodsRecord')
			->where(['status' => $model::STATUS_W, 'open_time' => ['elt', time()]])
			->select();
		if(!$rows) {
			$str .= '没有需要开奖的记录'."\r\n";
			die($str);
		}
		
		$buyModel = new BuyRecord();
		foreach($rows as $row) {
			$model->startTrans();
			try {
				//计算开奖结果,如果指定了开奖，那么使用指定号码
				if($row['is_robot'] && $row['buy_id']) {
					$openNo = $row['buy_id'];
				} else {
					$openNo = $buyModel->getOpenNo($row['end_time'], $row['total_number']);
				}
				
				//更改记录状态
				$res = Db::name('goodsRecord')
					->where(['id' => $row['id']])
					->update([
						'status' => $model::STATUS_F,
						'winning_id' => $openNo
					]);
				if(!$res) {
					throw new Exception('更改记录状态出错');
				}
				
				//更改购买记录状态
				$buyRes = Db::name('buyRecord')
					->where(['goods_record_id' => $row['id']])
					->update([
						'status' => $buyModel::STATUS_N
					]);
				if(!$buyRes) {
					throw new Exception('更改购买记录状态出错');
				}
				
				//更改中奖的人状态为
				$winRow = Db::name('buyRecord')
					->where('find_in_set(\''.$openNo.'\',no_list) and goods_record_id = '.$row['id'])
					->find();
				if($winRow) {
					$winRes = Db::name('buyRecord')
						->where(['id' => $winRow['id']])
						->update([
							'status' => $buyModel::STATUS_Y
						]);
					if(!$winRes) {
						throw new Exception('更改中奖人状态出错');
					}
					
					//生成中奖人的订单
					
					$orderRes = Db::name('order')
						->insert([
							'user_id' => $winRow['user_id'],
                            'goods_record_id' => $row['id'],
							'create_time' => time(),
							'update_time' => time(),
							'goods_id' => $row['goods_id'],
						]);
				
					if(!$orderRes) {
						throw new Exception('生成中奖订单出错');
					}
					
				}
				
				$model->commit();
				$str .= $row['id'].'开奖成功'."\r\n";
				
			} catch (Exception $e) {
				$model->rollback();
				$str .= $e->getMessage()."\r\n";
				continue;
			}
			
		}
		
		echo $str;
	}
}
